#!/bin/bash

function print_output() {

  #Colors
  RED=$(tput setaf 1)
  GREEN=$(tput setaf 2)
  YELLOW=$(tput setaf 3)
  NC=$(tput sgr0)

  name1=$(echo "${*:2:$#-1}" | sed 's/^"\(.*\)"$/\1/')

  Renamed=$1

  if [ $1 == D ]; then
    long_name="${RED}Deleted${NC}: $name1"
    filesize=0
    return 0
  fi

  if [ ${Renamed:0:1} == R ]; then
    long_name="${RED}Renamed${NC}: $name1"
    filesize=0
    return 0
  fi

  #Find file size
  var=$(du -s "${name1}")
  array=($var)
  filesize=${array[0]}
  # echo $filesize
  var=$(du -sh "${name1}")

  #Display file depending on git status
  case $1 in
  M*) long_name="${RED}Modified${NC}: $var" ;;
  A*) long_name="${GREEN}Added${NC}: $var" ;;
  U*) long_name="${GREEN}Updated${NC}: $var" ;;
  C*) long_name="${YELLOW}Copied${NC}: $var" ;;
  # R*) long_name="${RED}Renamed${NC}: $var" ;;
  '??') long_name="${RED}Untracked${NC}: $var" ;;
  esac
  # $(awk "BEGIN {printf \"%.1f\",${var}/1000000}")
  test=$((filesize / 1024 / 2))
  #echo $test
  if (($test > 10)); then
    return 1
  else
    return 0
  fi

  # return $var
}

function add_files() {
  echo $(touch .gitignore)
  echo >>.gitignore
  while read status; do
    if [ ${status:0:1} == D ]; then
      continue
    fi

    #Find file size
    name=${status:2}
    file=$(echo $name)
    file=${file//\"/}
    # echo $file
    var=$(du -s "${file}")
    array=($var)
    filesize=${array[0]}
    mb=$((filesize / 1024 / 2))

    if (($mb > 10)); then
      echo $file >>.gitignore
    fi
  done < <(git status --porcelain)
}

large_files=()

while read status_file; do
  print_output $status_file
  large_files+=($?)
  size="$filesize $long_name"
  size=$size$(echo -e "\n ")
  size_all=$size_all$size
  # echo "$size"
done < <(git status --porcelain)

size_all_n=$(echo "${size_all}" | sort -n | tr -s '\n' | awk '{$1=null;print $0}' | sed '1d' | sed 's/.//')
echo "$size_all_n"

for i in ${large_files[@]}; do
  #echo $i
  if (($i == 1)); then
    read -p "Do you want to add your files larger than 10mb to your .gitignore? [Y/N] " answer
    case $answer in
    [Yy]*)
      add_files
      break
      ;;
    [Nn]*) exit ;;
    *) echo "Please answer Y or N." ;;
    esac
  fi
done
